package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.yami.shop.bean.model.MeltCloudUser;
import com.yami.shop.bean.model.MeltCloudUserBlacklist;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageUtil;
import com.yami.shop.service.MeltCloudUserBlacklistService;
import com.yami.shop.service.MeltCloudUserService;
import com.yami.shop.util.SendUtil;
import io.rong.RongCloud;
import io.rong.methods.user.blacklist.Blacklist;
import io.rong.models.Result;
import io.rong.models.response.BlackListResult;
import io.rong.models.user.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RongYunUserWhiteServiceImpl {
    @Autowired
    private RongCloud rongCloud;

    private Blacklist BlackList;

    @Autowired
    private MeltCloudUserService userService;

    @Autowired
    private MeltCloudUserBlacklistService meltCloudUserBlacklistService;

    @PostConstruct
    public void init() {
        this.BlackList = rongCloud.user.blackList;
    }

    /**
     * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/black.html#add
     * 添加自己的黑名单
     */
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<String> userBlacklistAdd(String userId, List<String> userBlacklist) throws Exception {
        List<MeltCloudUserBlacklist> meltCloudUserBlacklistList = new ArrayList<>();
        List<UserModel> blacklist = new ArrayList<>();
        for (String id : userBlacklist) {
            LambdaQueryWrapper<MeltCloudUserBlacklist> getone = new LambdaQueryWrapper<MeltCloudUserBlacklist>().eq(MeltCloudUserBlacklist::getUserId,userId).eq(MeltCloudUserBlacklist::getToUserId,id);
            MeltCloudUserBlacklist one = meltCloudUserBlacklistService.getOne(getone);
            if(ObjectUtils.isNotEmpty(one)){
                one.setDelflag("1");
                meltCloudUserBlacklistService.updateById(one);
            }else{
                // 添加黑名单关系
                MeltCloudUserBlacklist meltCloudUserBlacklist = new MeltCloudUserBlacklist();
                meltCloudUserBlacklist.setUserId(userId);
                meltCloudUserBlacklist.setToUserId(id);
                meltCloudUserBlacklistList.add(meltCloudUserBlacklist);
            }
            UserModel blackUser = new UserModel().setId(id);
            blacklist.add(blackUser);
        }
        UserModel[] blacks = blacklist.toArray(new UserModel[0]);
        UserModel user = new UserModel().setId(userId).setBlacklist(blacks);
        Result userAddBlacklistResult = BlackList.add(user);
        log.info("addBlacklist:  " + userAddBlacklistResult.toString());
        if (SendUtil.requestSuccess(userAddBlacklistResult)) {
            // 添加本地黑名单
            meltCloudUserBlacklistService.saveBatch(meltCloudUserBlacklistList);
            return ServerResponseEntity.success();
        }
        throw new YamiShopBindException("添加用户黑名单异常");
    }

    /**
     * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/black.html#remove
     * 将用户从黑名单中移除
     */
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<String> remove(String userId, List<String> userBlacklist) throws Exception {
        List<UserModel> blacklist = new ArrayList<>();
        for (String id : userBlacklist) {
            //修改状态
            LambdaUpdateWrapper<MeltCloudUserBlacklist> eq = new LambdaUpdateWrapper<MeltCloudUserBlacklist>()
                    .set(MeltCloudUserBlacklist::getDelflag,1)
                    .eq(MeltCloudUserBlacklist::getUserId, userId)
                    .eq(MeltCloudUserBlacklist::getToUserId, id);
            meltCloudUserBlacklistService.update(eq);
            UserModel blackUser = new UserModel().setId(id);
            blacklist.add(blackUser);
        }
        UserModel[] blacks = blacklist.toArray(new UserModel[0]);
        UserModel user = new UserModel().setId(userId).setBlacklist(blacks);
        Result removeResult = BlackList.remove(user);
        if (SendUtil.requestSuccess(removeResult)) {
            return ServerResponseEntity.success();
        }
        throw new YamiShopBindException("移除用户黑名单异常");
    }

    /**
     * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/black.html#getList
     * 获取某用户的黑名单列表方法
     */
    public ServerResponseEntity<PageVO<MeltCloudUser>> queryBlacklist(PageDTO pageDTO, String userId, String userName) throws Exception {
        UserModel user = new UserModel().setId(userId);
        BlackListResult result = BlackList.getList(user);
        log.info("query blacklist:  " + result.toString());
        if (SendUtil.requestSuccess(result)) {
            UserModel[] users = result.getUsers();
            List<UserModel> userModels = new ArrayList<>(Arrays.asList(users));
            if (CollectionUtil.isNotEmpty(userModels)) {
                List<String> list = userModels.stream().map(UserModel::getId).collect(Collectors.toList());
                PageVO<MeltCloudUser> data = PageUtil.doPage(pageDTO, () -> userService.list(new LambdaQueryWrapper<MeltCloudUser>().in(MeltCloudUser::getId, list)
                        .like(StrUtil.isNotEmpty(userName), MeltCloudUser::getUserName, userName)));
                return ServerResponseEntity.success(data);
            }
            return ServerResponseEntity.success();
        }
        throw new YamiShopBindException("获取用户的黑名单列表");
    }

    /**
     * 查询聊天对话是否拉黑
     * @param userId
     * @param touserId
     * @return
     */
    public ServerResponseEntity<Boolean> queryisBlack(String userId, String touserId) {
        LambdaQueryWrapper<MeltCloudUserBlacklist> eq = new LambdaQueryWrapper<MeltCloudUserBlacklist>().eq(MeltCloudUserBlacklist::getUserId, userId).eq(MeltCloudUserBlacklist::getToUserId, touserId).eq(MeltCloudUserBlacklist::getDelflag,0);
        MeltCloudUserBlacklist one = meltCloudUserBlacklistService.getOne(eq);
        if(ObjectUtils.isNotEmpty(one)){
            return ServerResponseEntity.success(true);
        }else{
            return ServerResponseEntity.success(false);
        }

    }
}
